package com.caigou.modules.forum.ui.forum

import android.os.Bundle
import android.text.TextUtils
import androidx.activity.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.caigou.comm.base.bean.AppBackgroundInfo
import com.caigou.comm.base.constants.AppConstants
import com.caigou.comm.base.constants.RouterPath
import com.caigou.comm.base.container.BaseActivity
import com.caigou.comm.base.ext.Resource
import com.caigou.comm.base.ext.observe
import com.caigou.comm.base.ext.openBrowser
import com.caigou.comm.base.ext.showToast
import com.caigou.comm.base.utils.Logger
import com.caigou.comm.base.widget.SpaceItemDecoration
import com.caigou.modules.forum.R
import com.caigou.modules.forum.adpter.ForumItemAdapter
import com.caigou.modules.forum.bean.AdItemBean
import com.caigou.modules.forum.bean.NoticeItemBean
import com.caigou.modules.forum.bean.PostBean
import com.caigou.modules.forum.databinding.ActivityForumBinding
import com.caigou.modules.forum.viewmodel.ForumViewModel
import com.caigou.modules.forum.viewmodel.LikeViewModel
import com.google.android.material.tabs.TabLayout
import dagger.hilt.android.AndroidEntryPoint

/**
 * @author #Suyghur.
 * Created on 2021/12/08
 */
@Route(path = RouterPath.Forum.PAGE_FORUM)
@AndroidEntryPoint
class ForumActivity : BaseActivity() {

    private lateinit var binding: ActivityForumBinding
    private val forumViewModel: ForumViewModel by viewModels()
    private val likeViewModel: LikeViewModel by viewModels()

    private var page = 1
    private val limit = 10
    private var totalPage = 0
    private var forumType = 1
    private var sort = 0

    private val sortNames = mutableListOf(
        "综合",
        "关注",
        "精华",
        "最多赞",
        "最新"
    )

    private val adList = mutableListOf<AdItemBean>()
    private val noticeList = mutableListOf<NoticeItemBean>()

    private val mAdapter: ForumItemAdapter by lazy {
        ForumItemAdapter(mutableListOf())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityForumBinding.inflate(layoutInflater)
        setContentView(binding.root)
        containerId = binding.forumLlContainer.id
        initView()
    }

    private fun initView() {
        ARouter.getInstance().inject(this)
        binding.forumRgSelector.setOnCheckedChangeListener { group, checkedId ->
            forumType = when (checkedId) {
                binding.forumBtnHk.id -> {
                    binding.forumLlContainer.setBackgroundResource(R.drawable.forum_hk_ticket_bg)
                    1
                }
                binding.forumBtnMacao.id -> {
                    binding.forumLlContainer.setBackgroundResource(R.drawable.forum_macao_ticket_bg)
                    2
                }
                binding.forumBtnSingapore.id -> {
                    binding.forumLlContainer.setBackgroundResource(R.drawable.forum_singapore_ticket_bg)
                    3
                }
                binding.forumBtnTw.id -> {
                    binding.forumLlContainer.setBackgroundResource(R.drawable.forum_tw_ticket_bg)
                    4
                }
                binding.forumBtnSoccer.id -> {
                    binding.forumLlContainer.setBackgroundResource(R.drawable.forum_soccer_ticket_bg)
                    5
                }
                else -> {
                    binding.forumLlContainer.setBackgroundResource(R.drawable.forum_hk_ticket_bg)
                    1
                }
            }
            page = 1
            fetchForumList()
        }

        sortNames.forEachIndexed { idx, value ->
            val tab = binding.forumTabLayout.newTab()
            tab.text = value
            binding.forumTabLayout.addTab(tab, idx)
        }

        binding.forumTabLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab?) {
                tab?.apply {
                    sort = position
                    page = 1
                    fetchForumList()
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab?) {
            }

            override fun onTabReselected(tab: TabLayout.Tab?) {
            }

        })

        binding.forumSwipeRefreshLayout.run {
            setColorSchemeColors(resources.getColor(R.color.caigou_theme_color))
            setOnRefreshListener {
                page = 1
                fetchForumList()
                fetchList()
            }
        }

        mAdapter.loadMoreModule.run {
            setOnLoadMoreListener {
                mAdapter.loadMoreModule.isEnableLoadMore = true
                fetchForumList()
            }
            isAutoLoadMore = true
            isEnableLoadMoreIfNotFullPage = false
        }
        binding.forumRecyclerView.run {
            layoutManager = LinearLayoutManager(this@ForumActivity)
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(SpaceItemDecoration(this@ForumActivity))
        }
        mAdapter.setOnItemClickListener { _, _, position ->
            val postId = mAdapter.getItem(position).id
            ARouter.getInstance().build(RouterPath.Forum.PAGE_FORUM_POST)
                .withInt(AppConstants.POST_ID, postId)
                .navigation()
        }
        mAdapter.setOnItemChildClickListener { adapter, view, position ->
            val item = mAdapter.getItem(position)
            when (view.id) {
                R.id.item_forum_ll_like -> {
                    if (AppBackgroundInfo.instance.hasLogin) {
                        if (item.like) {
                            showToast("您已经点过赞了")
                        } else {
                            likeViewModel.setPostLike(item.id, AppBackgroundInfo.instance.userBean!!.userId, item.userId)
                        }
                    } else {
                        ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
                    }
                }
            }
        }

        binding.forumLlPublish.setOnClickListener {
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Forum.PAGE_PUBLISH_POST)
                    .withInt(AppConstants.FORUM_TYPE, forumType)
                    .navigation()
            } else {
                showToast("请您先登录")
            }
        }

        binding.forumTvBack.setOnClickListener {
            finish()
        }

        binding.forumIvSearch.setOnClickListener {
            ARouter.getInstance().build(RouterPath.Forum.PAGE_FORUM_SEARCH)
                .withInt(AppConstants.FORUM_TYPE, forumType)
                .navigation()
        }

        val rankList = mutableListOf(
            "彩民之家粉丝排行榜",
            "彩民之家等级排行榜",
            "彩民之家魅力值排行榜",
            "彩民之家贡献值排行榜",
            "彩民之家高手积分排行榜"
        )
        binding.forumTsvRank.setDataSource(rankList)
        binding.forumTsvRank.startPlay()

        binding.forumTsvRank.setOnClickListener {
            val tag = when (binding.forumTsvRank.currentItemIndex) {
                0 -> RouterPath.Rank.TAG_FANS_RANK
                1 -> RouterPath.Rank.TAG_LEVEL_RANK
                2 -> RouterPath.Rank.TAG_CHARM_RANK
                3 -> RouterPath.Rank.TAG_CONTRIBUTION_RANK
                4 -> RouterPath.Rank.TAG_MASTER_RANK
                else -> RouterPath.Rank.TAG_FANS_RANK
            }
            if (AppBackgroundInfo.instance.hasLogin) {
                ARouter.getInstance().build(RouterPath.Rank.PAGE_RANK)
                    .withString(AppConstants.TARGET_FRAGMENT_TAG, tag)
                    .navigation()
            } else {
                ARouter.getInstance().build(RouterPath.Login.PAGE_LOGIN).navigation()
            }
        }

        binding.forumTsvAd.setOnClickListener {
            val item = adList[binding.forumTsvAd.currentItemIndex]
            openBrowser(item.url)
        }

        binding.forumTsvNotice.setOnClickListener {
            val item = noticeList[binding.forumTsvNotice.currentItemIndex]
            ARouter.getInstance().build(RouterPath.Forum.PAGE_NOTICE)
                .withInt(AppConstants.DATA_ID, item.id)
                .navigation()
        }

        fetchForumList()
        fetchList()
    }

    override fun observeViewModel() {
        super.observeViewModel()
        observe(forumViewModel.forumListLiveData, ::handleGetForumList)
        observe(likeViewModel.postLikeLiveData, ::handleSetPostLike)
        observe(forumViewModel.adListLiveData, ::handleGetAdList)
        observe(forumViewModel.noticeListLiveData, ::handleNoticeList)
    }

    override fun onResume() {
        super.onResume()
        binding.forumTsvRank.startPlay()
        binding.forumTsvAd.startPlay()
        binding.forumTsvNotice.startPlay()
    }

    override fun onPause() {
        super.onPause()
        binding.forumTsvRank.stopPlay()
        binding.forumTsvAd.stopPlay()
        binding.forumTsvNotice.stopPlay()
    }

    private fun handleGetForumList(result: Resource<PostBean>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.forumSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取论坛信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.forumSwipeRefreshLayout.isRefreshing = false
                if (result.data == null) {
                    return
                }
                totalPage = result.data!!.totalPage

                if (page == 1) {
                    mAdapter.setList(result.data!!.list)
                } else {
                    mAdapter.addData(result.data!!.list)
                }

                if (result.data!!.pageSize < limit) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    mAdapter.loadMoreModule.loadMoreComplete()
                }

                if (page >= totalPage) {
                    mAdapter.loadMoreModule.loadMoreEnd(false)
                } else {
                    page++
                }
            }
        }
    }

    private fun handleNoticeList(result: Resource<MutableList<NoticeItemBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取论坛信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                noticeList.clear()
                noticeList.addAll(result.data!!)
                val list = mutableListOf<String>()
                result.data?.forEach {
                    list.add(it.title)
                }
                binding.forumTsvNotice.setDataSource(list)
                binding.forumTsvNotice.startPlay()
            }
        }
    }

    private fun handleGetAdList(result: Resource<MutableList<AdItemBean>>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("获取论坛信息异常")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                if (result.data == null) {
                    return
                }
                adList.clear()
                adList.addAll(result.data!!)
                val list = mutableListOf<String>()
                result.data?.forEach {
                    list.add(it.title)
                }
                binding.forumTsvAd.setDataSource(list)
                binding.forumTsvAd.startPlay()
            }
        }
    }

    private fun handleSetPostLike(result: Resource<String>) {
        when (result) {
            is Resource.Loading -> {
                mDialog.show()
            }
            is Resource.DataError -> {
                mDialog.dismiss()
                binding.forumSwipeRefreshLayout.isRefreshing = false
                if (!TextUtils.isEmpty(result.errorMsg)) {
                    showToast(result.errorMsg)
                } else {
                    showToast("点赞失败")
                }
            }
            is Resource.Success -> {
                mDialog.dismiss()
                binding.forumSwipeRefreshLayout.isRefreshing = false
                result.data?.apply {
                    showToast(this)
                    page = 1
                    fetchForumList()
                }
            }
        }
    }

    private fun fetchForumList() {
        val userId = if (AppBackgroundInfo.instance.hasLogin) {
            AppBackgroundInfo.instance.userBean!!.userId
        } else {
            ""
        }
        forumViewModel.getForumList(page, limit, forumType, sort, userId)
    }

    private fun fetchList() {
        forumViewModel.getNoticeList()
        forumViewModel.getAdList()
    }
}